package com.wsoft.interceptor;

import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wsoft.constant.CommonConstant;
import com.wsoft.constant.RedisKeyConstant;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.service.RedisService;
import com.wsoft.utils.FileUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 配置文件上传拦截, 拦截大于指定值的
 * @Author z001
 * @Date 2024/10/15 18:24
 */
@Component
public class FileUploadInterceptor implements HandlerInterceptor {

    @Resource
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Object object = redisService.get(RedisKeyConstant.CONFIG_CACHE_ALL);
            //获取最大请求大小
            Long limit = getTrafficLimit(object);
            if(null == limit){
                return true;
            }
            for (MultipartFile file : multipartRequest.getFileMap().values()) {
                if (file.getSize() > limit * FileUtil.MB) {
                    Asserts.fail("[oss.illegal.request]");
                    response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "File size exceeds the maximum limit of " + limit + "MB");
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 获取redis中 config表 file 缓存
     * @param configCache
     * @return
     */
    private Long getTrafficLimit(Object configCache){
        Map<String, Object> map = JSONObject.parseObject(JSONArray.parseArray(JSON.toJSONString(configCache)).get(0).toString());
        JSONObject fileMap = JSONObject.parseObject(map.get(CommonConstant.OSS_CONFIG_FILE).toString());
        Object object = fileMap.get(CommonConstant.OSS_TRAFFIC_LIMIT);
        if(ObjUtil.isEmpty(object)){
            return null;
        }
        return Long.valueOf(object.toString());
    }
}
